import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/components/Login.vue'
import Register from '@/components/Register.vue'

// 路由懒加载的格式
// const Login = () => import('@/components/Login.vue')
const Home = () => import('@/components/Home.vue')

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login },
  { path: '/register', component: Register },
  {
    path: '/home',
    component: Home,
    redirect: '/home/userManagement',
    children: [
      {
        path: 'userManagement',
        component: () => import('@/components/user/userManagement.vue'),
      },
      {
        path: 'orders',
        component: () => import('@/components/order/Order.vue'),
      },
      { path: 'cars', component: () => import('@/components/cars/Car.vue') },
      {
        path: 'logistics',
        component: () => import('@/components/logistics/Logistics.vue'),
      },
      {
        path: 'notice',
        component: () => import('@/components/notice/Notice.vue'),
      },
    ],
  },
]
const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes,
})

// 挂载路由导航守卫
router.beforeEach((to, from, next) => {
  // 跳转的地址为‘/login’ ,跳转到登录页
  if (to.path === '/login') return next()
  // 获取token
  const tokenStr = sessionStorage.getItem('token')
  // 如果token 为 空，强制跳转到登录页
  if (!tokenStr) return next('/login')
  next()
})
export default router
